package com.zk.shop.util;

import com.zk.shop.entity.CartItem;
import com.zk.shop.entity.Goods;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车的cookie工具类
 */
public class CartCookieUtil {

    /**
     * 获取cookie中名为 cart 的cookie
     * @param request HttpServletRequest
     * @return 返回空或者名为cart的cookie
     */
    public static Cookie getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        Cookie cartCookie = null;
        for(Cookie cookie : cookies){
            if("cart".equals(cookie.getName())){
                cartCookie = cookie;
            }
        }
        return cartCookie;
    }

    /**
     * 获取Cookie中的购物车列表
     * @param request HttpServletRequest
     * @return 返回空或者购物车列表
     */
    public static List<CartItem> getCart(HttpServletRequest request){
        //定义空购物车列表
        List<CartItem> cartItemList = new ArrayList<>();
        String value = "";
        //获取Cookie
        Cookie cartCookie = getCookie(request);
        //如果不为空则遍历获取
        if(cartCookie != null){
            try {
                value = URLDecoder.decode(cartCookie.getValue(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //如果不为空或者空字符串
            if(value != null && ! "".equals(value)){
                String[] arrValue = value.split("==");
                for (String val : arrValue) {
                    String[] arrVal = val.split("=");
                    CartItem item = new CartItem();
                    Goods goods = new Goods();
                    goods.setGoodsId(Integer.parseInt(arrVal[0]));
                    goods.setGoodsName(arrVal[1]);
                    goods.setPrice(Double.parseDouble(arrVal[2]));
                    goods.setImage(arrVal[3]);
                    item.setGoods(goods);
                    item.setBuyNum(Integer.parseInt(arrVal[4]));
                    cartItemList.add(item);
                }
            }
        }
        return cartItemList;
    }

    /**
     * 制作cookie value
     * @param cartItemList 购物车列表
     * @return 返回 cookie 字符串
     */
    public static String makeCookieValue(List<CartItem> cartItemList){
        StringBuffer buffer = new StringBuffer();
        for (CartItem item : cartItemList) {
            buffer.append(item.getGoods().getGoodsId() + "=" + item.getGoods().getGoodsName() + "=" + item.getGoods().getPrice() + "="
                    + item.getGoods().getImage() + "=" + item.getBuyNum() + "==");
        }
        return buffer.toString().substring(0, buffer.toString().length() - 2);
    }
}
